<?php 
if (!defined('BASEPATH')){
	exit('No direct script access allowed');
}

/**
 * Adminlog Controller
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class Sales extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('sales');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('sales_model');
                        $this->load->model('user_model');
			$this->set_controller('sales');
			$this->set_model($this->sales_model);
		}
                $this->load->model('salesphone_model');
                $this->load->model('sales_model');
                $this->load->model('area_model');
                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
                
	}

        private function direct(){
            $checkDirect = $_SERVER['HTTP_REFERER'];
            if(!isset($checkDirect)){
                redirect(base_url());
            }
        }
        
        private function menuTop(){
            $this->load->model('stats_model');
            $user_info                          = $this->stats_model->get_user_info($this->stats_model->get_user_id());
            $this->view_data['role_by_group']   = $user_info['role_list'];
            $this->view_data['username']        = $user_info['username'];
            return $this->view_data;
        }

        public function add($params = null){
            $this->direct();//prevent direct
            $this->menuTop();
            if($this->input->server('REQUEST_METHOD')=='POST'){
                
                $this->view_data["sales"]                                       = new stdClass();
                $this->view_data["sales"]->name                                 = $this->input->post('name');
                $this->view_data["sales"]->type                                 = $this->input->post('type');
                $this->view_data["sales"]->phone                                = $this->input->post('phone');
                $this->view_data["sales"]->address                              = $this->input->post('address');
                $this->view_data["sales"]->province                             = $this->input->post('province');
                $this->view_data["sales"]->email                                = $this->input->post('email');
                $this->view_data["sales"]->area                                 = $this->input->post('area');
                $this->view_data["sales"]->communication                        = $this->input->post('communication');
                $this->view_data["sales"]->callquality                          = $this->input->post('callquality');
                $this->view_data["sales"]->interested                           = $this->input->post('interested');
                $this->view_data["sales"]->frequency                            = $this->input->post('frequency');
                $this->view_data["sales"]->note_customers                       = $this->input->post('note_customers');
                $this->view_data["sales"]->note_staffs                          = $this->input->post('note_staffs');
                $this->view_data["sales"]->owner                                = $this->session->userdata['user_id'];
                $this->view_data["sales"]->lastupdated                          = time();
                $this->view_data["sales"]->phone_callstatus                     = $this->input->post('phone_callstatus');
                $this->view_data["sales"]->phone_calltime                       = $this->input->post('phone_calltime');
                
                $phone_exists   = $this->sales_model->find_by(array('phone' => $this->view_data["sales"]->phone));
                
                if($phone_exists){
                    if($phone_exists[0]->type==2){
                        $query = $this->salesphone_model->updatePhoneActive($phone_exists[0]->phone);
                    }
                    $this->view_data['info_phone'] = array(
                        'user_info'                 =>      $this->sales_model->getInfoUserByParams(array('key'=>'id','value'=>$phone_exists[0]->owner)),
                        'phone_info'                =>      $phone_exists,
                        'query'                     =>      $query
                    );
                   
                    $this->load->view('auth/sales/phone_daily', $this->view_data);
                } else {
                    $query = $this->salesphone_model->updatePhoneActive($this->input->post('phone'));
                    if(!$query){
                        die("DATABASE ERROR! DATABASE BI QUÁ TAI! LIEN HE ADMIIN");
                    }
                }

                $agent_code                                     = $this->sales_model->getListAgentCode($this->session->userdata['agent_code']);
                $this->view_data["sales"]->agent_code           = $this->session->userdata['agent_code'];
                //exists customerID nếu customer ID bị trùng thì lấy số khác cho nó
                $loop = 1;
                while($loop < 4){
                    $this->view_data["sales"]->customerID       = $agent_code[1].$this->bookinglib->createCustomerID();
                    $r_exists                                   = $this->sales_model->find_by(array('customerID' => $this->view_data["sales"]->customerID));
                    if(empty($r_exists)){
                        unset($loop);
                        break;
                    } else {
                        $loop++;
                    }
                }
                    
                $info = $this->checkVoiceIp($this->view_data["sales"],'update');
                if($info){
                    $this->view_data["sales"]->phone_calltime   = ($info->Thoigiangoi)?$info->Thoigiangoi:'0';
                }

                $params                                         = $this->sales_model->create($this->view_data["sales"]);
                $customerID                                     = $this->view_data["sales"]->customerID;                        

                /*
                 * update static phone
                 */
                $this->load->model('statistic_model');
                $calltime = array(
                    'term'              =>  'phone_calltime',
                    'owner'             =>  $this->session->userdata['user_id'],
                    'lastupdated'       =>  date("Y-m-d"),
                    'phone_calltime'    =>  $this->view_data["sales"]->phone_calltime
                );
                $this->statistic_model->updateCallTime($calltime);
                unset($calltime);unset($this->view_data["sales"]);

                if($customerID){
                        $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                        $paramAdminLog  = array(
                            'userid'            => $this->session->userdata['user_id'],
                            'lastLogin'         => date('Y-m-d :H:i:s',time()),
                            'ip'                => $_SERVER['REMOTE_ADDR'],
                            'logAction'         => $this->lang->line("add_sales_success").' -- SDT='.$this->input->post('phone'),
                            'agent_code'        => $this->session->userdata['agent_code']
                        );
                        $this->user_model->insertUserAdminLog($paramAdminLog);
                        redirect('auth/sales/index/edit/'.$customerID);
                }
            } //if($this->input->server('REQUEST_METHOD')=='POST'){
            
            $this->load->model('listcustomers_model');
            $this->load->model('language_model');
            $this->view_data['js'] = array(
                            base_url().'static/templates/backend/js/main.js'
            );            
            $this->view_data['fone']    =   $this->autoRequestFone();
            
            $sphone   = $this->sales_model->find_by(array('phone' => $this->view_data["sales"]->phone),'phone');
            if($sphone){//neu phone nam trong list sale thi tiep tuc tim
                $this->salesphone_model->updatePhoneActive($this->view_data['fone']);
                $paramAdminLog  = array(
                    'userid'            => $this->session->userdata['user_id'],
                    'lastLogin'         => date('Y-m-d :H:i:s',time()),
                    'ip'                => $_SERVER['REMOTE_ADDR'],
                    'logAction'         => 'UPDATE STATUS PHONE LIST SALES'.$this->view_data['fone'].' = 1',
                    'agent_code'        => $this->session->userdata['agent_code']
                );
                $this->user_model->insertUserAdminLog($paramAdminLog);
                redirect('auth/sales/add');
            }
            $scustomer = $this->listcustomers_model->searchCustomers(NULL,$this->view_data['fone']);
            if($scustomer){//neu phone nam trong list contacts thi tiep tuc tim
                $this->salesphone_model->updatePhoneActive($this->view_data['fone']);
                $paramAdminLog  = array(
                    'userid'            => $this->session->userdata['user_id'],
                    'lastLogin'         => date('Y-m-d :H:i:s',time()),
                    'ip'                => $_SERVER['REMOTE_ADDR'],
                    'logAction'         => 'UPDATE STATUS PHONE '.$this->view_data['fone'].' = 1',
                    'agent_code'        => $this->session->userdata['agent_code']
                );
                $this->user_model->insertUserAdminLog($paramAdminLog);
                redirect('auth/sales/add');
            }
            if($this->view_data['fone']==""){
                $this->load->view('auth/sales/hetso', $this->view_data);
            }

            $paramAdminLog  = array(
                'userid'            => $this->session->userdata['user_id'],
                'lastLogin'         => date('Y-m-d :H:i:s',time()),
                'ip'                => $_SERVER['REMOTE_ADDR'],
                'logAction'         => '[SalesPrepared] Chuẩn bị khởi tạo Sales KH SDT = '.$this->view_data['fone'],
                'agent_code'        => $this->session->userdata['agent_code']
            );
            $this->user_model->insertUserAdminLog($paramAdminLog);
            if(in_array($this->session->userdata['user_id'],array('152','168','169','187'))){
                $this->load->view('auth/sales/addVoiceIp', $this->view_data);//voice IP
            } else {
                $this->load->view('auth/sales/add', $this->view_data);// voice thuong
            }   
        }
        
        public function getphone(){
            $this->direct();//prevent direct
            //step 1 : Save phone to system
            if($this->input->get('phone') && $this->input->get('term') == "phone_busy"){
                $this->view_data['getphone']        =   new stdClass();
                $this->view_data['getphone']->phone =   $this->input->get('phone');
                $result                             = $this->checkVoiceIp($this->view_data['getphone'],'getphone');
                
                $this->load->model('statistic_model');
                $calltime = array(
                    'term'              =>  'phone_calltime',
                    'owner'             =>  $this->session->userdata['user_id'],
                    'lastupdated'       =>  date("Y-m-d"),
                    'phone_calltime'    =>  ($result->Thoigiangoi)?$result->Thoigiangoi:'0'
                );
                $this->statistic_model->updateCallTime($calltime);
                unset($calltime);
                unset($this->view_data['getphone']);
            }
            //step 2 : active other phone
            $term   = ($this->input->get('term'))?$this->input->get('term'):'';           
            
            $this->load->model('getphone_model');
            $getphone               = $this->getphone_model->getphone();
            if(empty($getphone)){
                die("");
            }
            if($term == "request" || $term == "phone_busy"){
                $phoneNew      = $this->sales_model->updateStatusPhone($getphone[0]->phone,'1');
                if(!$phoneNew){
                    die("fail");
                }
            }

            if($term != 'request'){
                $phone          = ($this->input->get('phone'))?$this->input->get('phone'):'';
                $phoneOld       = $this->sales_model->updateStatusPhone($phone,'0');

                $this->load->model('statistic_model');
                $data = array(
                    'term'          => $term,
                    'owner'         => $this->session->userdata['user_id'],
                    'lastupdated'   => date("Y-m-d")
                );
                
                $query = $this->statistic_model->updateAction($data);
                if(!$query){
                    $this->view_data["datas"]                   = new stdClass();
                    $this->view_data["datas"]->$term            = 1;
                    $this->view_data["datas"]->owner            = $data['owner'];
                    $this->view_data["datas"]->agent_code       = $this->session->userdata['agent_code'];
                    $this->view_data["datas"]->lastupdated      = $data['lastupdated'];
                    
                    $this->statistic_model->create($this->view_data["datas"]);
                }
            }
            die($getphone[0]->phone);
        }
        
        public function search(){
                $this->direct();//prevent direct
                
                $this->view_data	= array();
		$this->view_data['flash_message_error']         = $this->session->flashdata('flash_message_error');
		$this->view_data['flash_message']		= $this->session->flashdata('flash_message');
		
                if($this->input->server('REQUEST_METHOD')=='POST'){
                    $this->menuTop();
                    $data = array(
                        'phone'     =>  $this->input->post('phone'),
                        'owner'     =>  $this->session->userdata('user_id')
                    );
                    $paramAdminLog  = array(
                        'userid'            => $this->session->userdata['user_id'],
                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                        'ip'                => $_SERVER['REMOTE_ADDR'],
                        'logAction'         => '[SalesSearch] Tìm kiếm SĐT: '.$this->input->post('phone') . ' thành công!',
                        'agent_code'        => $this->session->userdata['agent_code']
                    );
                    $this->user_model->insertUserAdminLog($paramAdminLog);
                    
                    $this->view_data['lists']     =    $this->sales_model->search($data);
                    $this->load->view('auth/sales/search_display', $this->view_data);
                }
                
		if($this->database_connect_status){
                        $this->menuTop();
                        $this->load->view('auth/sales/search', $this->view_data);
                } else {
                        $this->view_data['flash_message']	= $this->lang->line('database_connect_failed');
                        $this->load->view('templates/backend/error', $this->view_data);	
                }
        }
        
        public function statistic(){
                $this->direct();//prevent direct
                $this->load->model('voicelog_model');
		if($this->database_connect_status){
                        $this->menuTop();
                        $data = array(
                            'onwer'         => $this->session->userdata('user_id'),
                            'lastupdated'   => date('Y-m-d')
                        );
                        $todate = strtotime(date('Y-m-d 00:00:01'));
                        $this->load->model('statistic_model');
                        $this->view_data['result']              = $this->statistic_model->selectAllById($data);
                        $this->view_data['type']                = array(
                            $this->statistic_model->countTypeSales(1,$todate,$data['onwer']),//get type = 1
                            $this->statistic_model->countTypeSales(2,$todate,$data['onwer'])//get type = 2
                        );
                        
                        $this->load->model('booking_model');
                        $this->view_data['bookinghold']             = $this->booking_model->bookinghold($data['onwer']);
                        
                        $this->load->model('bookhistory_model');
                        $this->view_data['bookingOk']               = $this->bookhistory_model->bookingOk($data['onwer']);
                        
                        $this->load->view('auth/sales/statistic', $this->view_data);
                } else {
                        $this->view_data['flash_message']	= $this->lang->line('database_connect_failed');
                        $this->load->view('templates/backend/error', $this->view_data);	
                }
        }
        
        protected function update($params=NULL){
                $this->direct();//prevent direct
		if($this->input->server('REQUEST_METHOD')=='POST'){
                        $this->view_data["sales"]                               = new stdClass();
                        $this->view_data["sales"]->name                         = $this->input->post('name');
                        $this->view_data["sales"]->type                         = $this->input->post('type');
                        $this->view_data["sales"]->phone_callstatus             = $this->input->post('phone_callstatus');
                        $this->view_data["sales"]->address                      = $this->input->post('address');
                        $this->view_data["sales"]->email                        = $this->input->post('email');
                        $this->view_data["sales"]->province                     = $this->input->post('province');
                        $this->view_data["sales"]->area                         = $this->input->post('area');
                        $this->view_data["sales"]->communication                = $this->input->post('communication');
                        $this->view_data["sales"]->callquality                  = $this->input->post('callquality');
                        $this->view_data["sales"]->interested                   = $this->input->post('interested');
                        $this->view_data["sales"]->frequency                    = $this->input->post('frequency');
                        $this->view_data["sales"]->note_customers               = $this->input->post('note_customers');
                        $this->view_data["sales"]->note_staffs                  = $this->input->post('note_staffs');
                        $this->view_data["sales"]->owner                        = $this->session->userdata['user_id'];
                        $this->view_data["sales"]->agent_code                   = $this->session->userdata['agent_code'];
                        $this->view_data["sales"]->lastupdated                  = time();

                        $this->load->helper('form');
                        $this->load->helper('character');
                        $this->load->helper('form');
                        $this->load->library('form_validation');
                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $rules = array(
                            array(
                                'field'   => 'name',
                                'label'   =>  $this->lang->line('name'),
                                'rules'   => 'trim|max_length[255]|xss_clean'
                            )
                        );

                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $this->form_validation->set_rules($rules);

                        if ($this->form_validation->run()==TRUE){
                            if(isset($params) && $params){
                                 //edit data
                                $this->sales_model->update($this->view_data["sales"], $params,array('customerID' => $params));
                                $logAction                     = $this->lang->line('update_sales_success').$params;
                                $customerID                    = $params;
                            }
                            
                            if($customerID){
                                    $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                                    $paramAdminLog  = array(
                                        'userid'            => $this->session->userdata['user_id'],
                                        'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                        'ip'                => $_SERVER['REMOTE_ADDR'],
                                        'logAction'         => $logAction,
                                        'agent_code'        => $this->session->userdata['agent_code']
                                    );
                                    $this->user_model->insertUserAdminLog($paramAdminLog);

                                    redirect('auth/sales/index/edit/'.$customerID);
                            }
                        }

            }
            
            $this->load->model('sales_model');
            $this->load->model('language_model');

            if(isset($params)){
                    $sales_query	= $this->sales_model->find_by(array('customerID' => $params));
                    
                    if(!isset($sales_query[0])){
                            $this->session->set_flashdata('flash_message', $this->lang->line('not_exists'));
                            redirect(site_url('auth/sales'));
                            exit();
                    }

                    $this->view_data['sales']				= $sales_query[0];
            }

            $this->view_data['js'] = array(
                            base_url().'static/templates/backend/js/main.js'
            );
            $this->view_data['css'] = array(
            );
            $this->load->view('auth/sales/edit', $this->view_data);
	}
        
        public function searchIdByPhone(){
            $this->direct();
           $this->load->model('getphone_model');
           $result = $this->getphone_model->searchIdByPhone($this->input->get('term',null),$this->session->userdata['user_id']);
           if(empty($result)){
               die("");
           } else {
               die($result[0]->customerID);
           }
        }
        
        public function autoRequestFone(){
            $this->load->model('getphone_model');
            $getphone               = $this->getphone_model->getphone();
            
            if(empty($getphone)){
                return '';
            }
            $phoneNew      = $this->sales_model->updateStatusPhone($getphone[0]->phone,'1');

            return $getphone[0]->phone;
        }
        
        public function updateStatus(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $phone          = $this->input->post('phone');
                $phoneNew       = $this->sales_model->updateStatusPhone($phone,'0');
            }
        }
        
        public function testPhoneExists(){
            
            $phone_exists   = $this->sales_model->find_by(array('phone' => $this->input->post('phone')));

            if(empty($phone_exists)){
                die("0");
            } else {
                $this->salesphone_model->updatePhoneActive($this->input->post('phone'));
                die("1");
            }
            
        }
        
        public function checkVoiceIp($param,$function) {
            if(in_array($this->session->userdata['user_id'],array('152','168','169','187'))){
                $phone = $param->phone;
                //so dt test
                //$phone  = "0912089289";
                $xml = simplexml_load_file(VOICE_IP_API.$phone);
                $arr = $this->toArray($xml->user);
                
                $this->view_data['voiceIp']                             = new stdClass();
                $this->view_data['voiceIp']->SoGoi                      = ($arr['SoGoi'])?$arr['SoGoi']:'';
                $this->view_data['voiceIp']->SoNhan                     = ($arr['SoNhan'])?$arr['SoNhan']:$phone;
                $this->view_data['voiceIp']->Trangthai                  = ($arr['Trangthai'])?$arr['Trangthai']:'';
                $this->view_data['voiceIp']->Thoigiangoi                = ($arr['Thoigiangoi'])?$arr['Thoigiangoi']:'';
                $this->view_data['voiceIp']->ThoigianTinhCuoc           = ($arr['ThoigianTinhCuoc'])?$arr['ThoigianTinhCuoc']:'';
                $this->view_data['voiceIp']->owner                      = $this->session->userdata['user_id'];
                $this->view_data['voiceIp']->lastupdated                = date("Y-m-d H:i:s");

                $this->load->model('voicelog_model');
                $query = $this->voicelog_model->create($this->view_data['voiceIp']);

                if(empty($arr)){
                    if($function == "update"){
                        $this->session->set_flashdata('flash_message', 'Hệ thống phát hiện cuoc goi SDT '.$phone.' chua ket thuc mà đã nhan lưu thông tin! Hệ thống đã log lại hành động của bạn');
                        redirect(site_url('auth/sales'));
                    }
                } else {
                    return $this->view_data['voiceIp'];
                }
                
            } else {
                //trường hợp k dùng voiceIp thì k làm gì
                return '';
            }
        }
        
        function toArray(SimpleXMLElement $xml) {
            $array = (array)$xml;

            foreach ( array_slice($array, 0) as $key => $value ) {
                if ( $value instanceof SimpleXMLElement ) {
                    $array[$key] = empty($value) ? NULL : toArray($value);
                }
            }
            return $array;
        }
}

/* End of file sales.php */
/* Location: ./application/controllers/auth/sales.php 

Ngaygoi: thời gian bắt đầu cuộc gọi
SoGoi: số máy gọi đi
SoNhan: số máy nhận
Trangthai: trạng thái cuộc gọi (ANSWERED, NO ANSWERED)
Thoigiangoi: thời gian của cuộc gọi từ lúc bắt đầu tới khi disconnect (bao gồm cả dialing)
ThoigianTinhCuoc: thời gian cuộc gọi kết nối
*/